package com.gjy.redis.controller;

import com.gjy.redis.domain.AjaxResult;
import com.gjy.redis.domain.vo.ZsetAddRequest;
import org.redisson.Redisson;
import org.redisson.api.RScoredSortedSet;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-07-13 15:53:56
 */
@RestController
@RequestMapping("/zset")
public class SortedSetController {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private Redisson redisson1;

    @SuppressWarnings("all")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody ZsetAddRequest request) {

        RScoredSortedSet<Object> set = redisson1.getScoredSortedSet(request.getKey());
        Map<Object, Double> map = new HashMap<>();

        request.getMembers().forEach(member -> {
            map.put(member.getMember(), member.getScore());
        });
        int add = set.addAll(map);

        return AjaxResult.builder().data(add).build();
    }

    @PostMapping("/count")
    public AjaxResult count() {
        ZSetOperations<String, Object> set = redisTemplate.opsForZSet();
        Long count = set.count("Z_1", Integer.MIN_VALUE, Integer.MAX_VALUE);
        return AjaxResult.builder().data(count).build();
    }
}
